"""
python-gitlab API文档：https://python-gitlab.readthedocs.io/en/v3.3.0/gl_objects/branches.html
"""

import gitlab
import os
# from app01.log import LogInterface
from utils.views import FsLog


# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",private_token='glpat-fJq6ugNWqxvnUQW8ouJP')
# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",oauth_token='glpat-4BKDNLYbyo4UtS2fnby3')
# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",private_token='glpat-xA7kMnoyabKLu6ZwzJdb')

# ## gitlab.test.ihomecloud.cn环境的aihma-cloud管理token
# gl = gitlab.Gitlab(url="http://gitlab.test.ihomecloud.cn/",oauth_token='glpat-xA7kMnoyabKLu6ZwzJdb')

## gitlab.test.ihomecloud.cn环境的aihma-cloud管理token
# gl = gitlab.Gitlab(url="http://git.bsphpro.com", oauth_token='glpat-WeTwtaG4ifaHPYwwUvC9',per_page=100)

## 返回 gitlab 客户端对象
def gitlabClient():
    gl = gitlab.Gitlab(url=f'{os.getenv("GITLAB_ADDR")}', oauth_token=f'{os.getenv("GITLAB_ACCESS_TOKEN")}', per_page=100, keep_base_url=True)
    return gl


## 通过 token 获取 Project
def projectsFromToken(gitlabClient):
    projectsList = gitlabClient.projects.list()
    return projectsList

## 通过 ProjectID 获取 Project 对象
def projectsFromId(gitlabClient, ProjectID_list):
    projects = gitlabClient.projects.list(all=True)
    projectList = []
    for project in projects:
        if project.id in ProjectID_list:
            projectList.append(project)
    return projectList

## 创建 tag
def createTag(gitlabClient, ProjectList, tagName):
    for project in ProjectList:
        project.tags.create({'tag_name': '1.0', 'ref': 'main'})





#
# class GitlabManage():
#     def __init__(
#             self,
#             url=None,
#             private_token=None,
#             oauth_token=None,
#             per_page=None,
#             pagination=None,
#             order_by=None,
#     ):
#         self.gl = gitlab.Gitlab(url=url, private_token=private_token,oauth_token=oauth_token,per_page=per_page,pagination=pagination,order_by=order_by)
#
#     ## 获取所有组
#     def GetAllProjects(self):
#         projects = self.gl.projects.list(all=True)
#         return projects
#
#     ## 通过ProjectID获取Project
#     def Get_Projects(self, ProjectID_list):
#         projects = self.gl.projects.list(all=True)
#         ProjectList = []
#         for project in projects:
#             if project.id in ProjectID_list:
#                 ProjectList.append(project)
#         return ProjectList
#
#     ## 获取到所有group
#     def Get_Groups(self):
#         self.groups = self.gl.groups.list()
#         return self.groups
#
#     ## 通过组名拿组id
#     def GetGroupID(self,GroupName):
#         groupid = None
#         for i in self.groups:
#             # print("111",i.id, i.name)
#             if i.name == GroupName:
#                 groupid = i.id
#                 # print("222",i.id,i.name)
#         return groupid
#
#     ## 通过组ID获取组内所有项目，返回project对象列表
#     def GetProjects(self, all: bool = False, search: str = None, group: str = None):
#         project_list = []
#         projects = self.gl.projects.list(all=all,search=search)
#         for project in projects:
#             groups = project.groups.list()
#             if groups and groups[0].name == group:
#                 project_list.append(project)
#         return project_list
#
#     ## 通过组ID获取组内所有项目，返回列表套字典
#     def GetProjects_dict(self,GroupID):
#         Groups = self.gl.groups.get(GroupID)
#         # print(group)
#         projects = Groups.projects.list()
#         GroupList = []
#         for i in projects:
#             GroupDict = {"id":"%s" %i.id,"ProjectName":"%s" %i.name}
#             GroupList.append(GroupDict)
#         return GroupList
#
#     ## 创建分支
#     def CreateBranch(self,project_obj,src_branch,dest_branch):
#         branch = project_obj.branches.create({'branch': dest_branch,'ref': src_branch})
#         return branch
#
#     ## 删除分支
#     def DeleteBranch(self,project_obj,branch_name):
#         branch = project_obj.branches.delete(branch_name)
#         # print("branch+++",branch)
#         return branch
#
#     ## 合并分支（后端）
#     def megre(self, src_br, dest_br):
#         # h = FeiShu_WebHook("j6f7yQlxsIXeP1PJ76K3Pb")
#         ## 拿到组下所有的项目
#         # projects = self.gl.projects.list(all=all, search=search)
#         projects = self.gl.projects.list()
#         print("aiaiaiaiai-------------------", projects)
#
#         ## 检查已有的合并请求
#         merge_cu = [{"msg":"当前存在开启状态的合并请求，请先检查！"},{"flg":[]}]
#         for project in projects:
#             mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#             # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
#             if mrs:
#                 # for mr in mrs:
#                 # merge_cu.append(project.name)
#                 merge_cu[1]["flg"].append(project.name)
#         if merge_cu[1]["flg"]:
#             # return "当前存在未开启状态的合并请求，请先检查！",merge_cu
#             FsLog("当前存在未开启状态的合并请求，请先检查！，%s\n" % merge_cu)
#
#             return merge_cu
#
#         ## 创建合并请求
#         for project in projects:
#             print("进来这里了")
#             try:
#                 mr = project.mergerequests.create({'source_branch': '%s' % src_br,
#                                                    'target_branch': '%s' % dest_br,
#                                                    'title': 'merge %s to %s' % (src_br, dest_br),
#                                                    'labels': ['from_pythonAPI']})
#                 # LogInterface.Build_Log.save_build("项目：%s 创建megre成功" % (project.name))
#                 FsLog("项目：%s 创建megre成功\n" % (project.name))
#                 print("项目：%s 创建megre成功" % (project.name))
#             except Exception as e:
#                 # LogInterface.Build_Log.save_build("项目：%s 创建merge失败，失败原因：%s" % (project.name, e))
#                 FsLog("项目：%s 创建merge失败，失败原因：%s\n" % (project.name, e))
#                 print("项目：%s 创建merge失败，失败原因：%s" % (project.name, e))
#
#         ## 检查已有的合并请求
#         merge_open = []
#         for project in projects:
#             mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#             # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
#             if mrs:
#                 for mr in mrs:
#                     merge_open.append(mr)
#
#         ## 合并
#         merge_ok = [{"msg": "合并完成！"}, {"flg": []}]
#         if merge_open:
#             for mr in merge_open:
#                 try:
#                     # print("++++++++++++++",mr)
#                     mr.merge()
#                     merge_ok[1]["flg"].append(mr.references["full"])
#                     # LogInterface.Build_Log.save_build("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     FsLog("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     print("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                 except Exception as e:
#                     # LogInterface.Build_Log.save_build("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
#                     FsLog("合并失败，项目：%s  merge_iid：%s 失败原因：%s\n" % (mr.references["full"], mr.iid, e))
#                     print("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
#                     try:
#                         mr.state_event = 'close'
#                         mr.save()
#                         # LogInterface.Build_Log.save_build("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                         FsLog("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                         print("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     except Exception as f:
#                         # LogInterface.Build_Log.save_build("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                         FsLog("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                         print("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#         print(merge_ok)
#         return merge_ok
#
#     ## 合并分支--前端
#     def megre_front(self, src_br, dest_br, projects):
#         ## 检查已有的合并请求
#         merge_cu = [{"msg": "当前存在开启状态的合并请求，请先检查！"}, {"flg": []}]
#         for project in projects:
#             mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#             # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
#             if mrs:
#                 # for mr in mrs:
#                 # merge_cu.append(project.name)
#                 merge_cu[1]["flg"].append(project.name)
#         if merge_cu[1]["flg"]:
#             # return "当前存在未开启状态的合并请求，请先检查！",merge_cu
#             return merge_cu
#
#         ## 创建合并请求
#         for project in projects:
#             try:
#                 mr = project.mergerequests.create({'source_branch': '%s'%src_br,
#                                                'target_branch': '%s'%dest_br,
#                                                'title': 'merge %s to %s' %(src_br,dest_br),
#                                                'labels': ['from_pythonAPI']})
#                 # FsLog("项目：%s 创建megre成功" % (project.name))
#                 print("项目：%s 创建megre成功" % (project.name))
#             except Exception as e:
#                 FsLog("项目：%s 创建merge失败，失败原因：%s" % (project.name, e))
#                 print("项目：%s 创建merge失败，失败原因：%s" % (project.name, e))
#
#         ## 检查已有的合并请求
#         merge_open = []
#         for project in projects:
#             mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#             # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
#             if mrs:
#                 for mr in mrs:
#                     merge_open.append(mr)
#
#         ## 合并
#         merge_ok = [{"msg":"合并完成！"},{"flg":[]}]
#         if merge_open:
#             for mr in merge_open:
#                 try:
#                     # print("++++++++++++++",mr)
#                     mr.merge()
#                     merge_ok[1]["flg"].append(mr.references["full"])
#                     # FsLog("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     print("合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                 except Exception as e:
#                     FsLog("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
#                     print("合并失败，项目：%s  merge_iid：%s 失败原因：%s" % (mr.references["full"], mr.iid, e))
#                     try:
#                         mr.state_event = 'close'
#                         mr.save()
#                         # FsLog("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                         print("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     except Exception as f:
#                         FsLog("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                         print("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#         print(merge_ok)
#         return merge_ok
#
#     ## 拿到open状态的合并请求项目名
#     def CuMerge_name(self):
#         ## 拿到组下所有的项目
#         projects = self.gl.projects.list()
#
#         ## 检查已有的合并请求
#         merge_cu = []
#         for project in projects:
#             mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#             if mrs:
#                 merge_cu.append(project.name)
#         return merge_cu
#
#     ## 拿到open状态的合并请求项目
#     def CuMerge_project(self):
#         ## 拿到组下所有的项目
#         projects = self.gl.projects.list()
#
#         ## 检查已有的合并请求
#         merge_open = []
#         for project in projects:
#             mrs = project.mergerequests.list(state='opened', order_by='updated_at')
#             # print("项目：%s   打开的合并请求：%s" %(project.name,mrs))
#             if mrs:
#                 for mr in mrs:
#                     merge_open.append(mr)
#         return merge_open
#
#     ## 将open状态的合并请求关闭
#     def CloseMerge(self, merge_cu):
#         if merge_cu:
#             # return "当前存在未开启状态的合并请求，请先检查！",merge_cu
#             for mr in merge_cu:
#                 # print("66666666",mr)
#                 try:
#                     mr.state_event = 'close'
#                     mr.save()
#                     # FsLog("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                     print("关闭合并成功，项目：%s  merge_iid：%s " % (mr.references["full"], mr.iid))
#                 except Exception as f:
#                     FsLog("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))
#                     print("项目：%s  关闭失败  mrid：%s   关闭错误信息：%s" % (mr.references["full"], mr.iid, f))




# class GL:
#     def __init__(self):
#         self.url = "https://gitlab.edccmss.cn"
#         self.token = "glpat-jwQDssmF4WQsASB9H9xj"
#         self.per_page = 100
#
#     def gitlabClient(self):
#         gl = gitlab.Gitlab(url=self.url, oauth_token=self.token, per_page=self.per_page)
#         return gl

# gl = gitlab.Gitlab(url="http://git.bsphpro.com", oauth_token='glpat-17yHK2BDqX2g3P-oF9Mk',per_page=100)
#
# ProjectID_List = [229, 262]
# project_list = []
# projects = gl.projects.list(all=True)
# for project in projects:
#     if project.id in ProjectID_List:
#         project_list.append(project)
# print(project_list)


# projects = gl.projects.list(all=True)
# # print(projects)
# for i in projects:
#     print(i.id,i.name)

# mrs = gl.mergerequests.list()
# mrs = gl.mergerequests.list(scope="all")
# group = gl.groups.get('aihma-cloud')
# mrs = group.mergerequests.list(all=True)



# projects = gl.projects.list()

# m = GitlabManage(url="http://git.bsphpro.com", oauth_token='glpat-WeTwtaG4ifaHPYwwUvC9',per_page=100)
# msg,flg = m.megre("release-V2.5.13","main")
# print("完成：",msg,flg)






# print(merge_open)

# ## 修改标签
# for mr in merge_open:
#     mr.labels = ['from_pythonAPI']
#     mr.save()
#     print(mr.labels)








#
# for project in projects:
#     if project.name == 'aihma-cloud-infra-common':
#         mrs = project.mergerequests.list()
#         for mr in mrs:
#             print(mr)

# mr = projects[0].mergerequests.get()
# print(mr)

# ## 生产git
# gl = GitlabManage(url="http://git.bsphpro.com", oauth_token='glpat-WeTwtaG4ifaHPYwwUvC9',per_page=100)
#
# # group = gl.Get_Groups()
# # groupid = gl.GetGroupID("aihma-cloud")
# projects = gl.GetProjects(group="aihma-cloud")
# for i in projects:
#     print(i.id,i.name,i.web_url)

# ## 创建分支
# for i in projects:
#     try:
#         branch = gl2.CreateBranch(i,"develop","feature1")
#         # branch = i.branches.create({'branch': 'feature1','ref': 'develop'})
#         print(branch,type(branch))
#         print("项目：%s 创建分支成功"%i.name)
#     # except gitlab.exceptions.GitlabCreateError:
#     except Exception as e:
#         print("项目：%s 创建分支失败：%s"%(i.name,e))

# ## 删除分支
# for i in projects:
#     try:
#         # branch = gl2.DeleteBranch(i,'feature1')  ##  删除分支，没有返回信息，不用给变量它了
#         gl.DeleteBranch(i,'feature1')
#         print("项目：%s 删除成功"%i.name)
#     except Exception as e:
#         print("项目：%s 删除失败：%s"%(i.name,e))






